package com.example.springstudy.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.dao.res.ShopListRes;
import com.example.springstudy.entity.Shop;
import com.example.springstudy.service.ShopService;
import com.example.springstudy.utils.DateUtils;
import com.example.springstudy.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/shop")
public class ShopController {
    @Autowired
    private ShopService shopService;

    @GetMapping("/list")
    public Result<ShopListRes> getList(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "100") Integer size){
        return Result.success(shopService.getShopList(page, size));
    }

    @SaveLog("修改店铺")
    @PostMapping("/addOrUpdate")
    public Result<Shop> addOrUpdateShop(@RequestBody Shop shop){
        try{
            Assert.hasText(shop.getName(), "name不能为空！");
            Assert.hasText(shop.getRegion(), "region不能为空！");
            Assert.hasText(shop.getAddress(), "address不能为空！");
            Assert.hasText(shop.getLongitude(), "longitude不能为空！");
            Assert.hasText(shop.getLatitude(), "latitude不能为空！");
            if(shop.getId()==null|| shop.getId()==0){
                shop.setCreateTime(DateUtils.defaultDate());
                return Result.success(shopService.saveShop(shop));
            } else {
                shop.setUpdateBy(SecurityUtils.getUserId());
                return Result.success(shopService.updateShop(shop));
            }

        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
}

